#include "GfxD3D9.h"

using namespace imGraphics;

D3D9MeshDriver::D3D9MeshDriver(void) {
	Vertices = NULL;
	Indices = NULL;
	NumVerts = NumFaces = 0;
	VertexBuffer = NULL;
	IndexBuffer = NULL;
}

D3D9MeshDriver::~D3D9MeshDriver(void) {
	Clear();
}

void D3D9MeshDriver::Clear(void) {
	if(VertexBuffer != NULL) {
		VertexBuffer->Release();
		VertexBuffer = NULL;
	}
	if(IndexBuffer != NULL) {
		IndexBuffer->Release();
		IndexBuffer = NULL;
	}
}

void D3D9MeshDriver::Hook(Vertex* _Verts, unsigned int _NumVerts, void* _Indices, unsigned int _NumFaces, unsigned int _IndexSize) {
	NumVerts = _NumVerts;
	NumFaces = _NumFaces;
	NumIndices = _NumFaces * 3;
	IndexSize = NumIndices * _IndexSize;

	HRESULT hr = g_DeviceD3D9->CreateVertexBuffer(NumVerts * sizeof(Vertex),
											0,//D3DUSAGE_WRITEONLY
											0,
											D3DPOOL_MANAGED,
											&VertexBuffer,
											NULL);

	if(FAILED(hr)) {
		MessageBox(NULL, "Failed to create Vertex Buffer", "Imagine - Error", MB_OK | MB_ICONERROR);
		return;
	};

	D3DFORMAT IndFMT = D3DFMT_INDEX16;
	if(_NumVerts >= 65536)
		IndFMT = D3DFMT_INDEX32;

	hr = g_DeviceD3D9->CreateIndexBuffer(IndexSize,
										 0,//D3DUSAGE_WRITEONLY
										 IndFMT,
										 D3DPOOL_MANAGED,
										 &IndexBuffer,
										 NULL);

	if(FAILED(hr)) {
		MessageBox(NULL, "Failed to create Index Buffer", "Imagine - Error", MB_OK | MB_ICONERROR);
		return;
	};

	VertexBuffer->Lock(0, sizeof(Vertex) * NumVerts, (void**)&Vertices, 0);
	memcpy(Vertices, _Verts, NumVerts * sizeof(Vertex));
	VertexBuffer->Unlock();

	IndexBuffer->Lock(0, IndexSize, (void**)&Indices, 0);//D3DLOCK_DISCARD
	memcpy(Indices, _Indices, NumIndices * sizeof(WORD));
	IndexBuffer->Unlock();

	return;
}

// Pre-render information, like lighting
void D3D9MeshDriver::Predraw(void) {
	g_DeviceD3D9->SetStreamSource(0, VertexBuffer, 0, sizeof(Vertex));
	g_DeviceD3D9->SetIndices(IndexBuffer);
}

// Draw your object
void D3D9MeshDriver::Draw(int Subset) {
	HRESULT hr = g_DeviceD3D9->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, NumVerts, 0, NumFaces);

	bool suc = SUCCEEDED(hr);

	return;
}